<template>
  <div ref="chartEl" style="height:100%"></div>
</template>
<script>
import * as echarts from "echarts";
export default {
  name: "charts",
  // props: {
  //   option: {
  //     type: Object,
  //     default: () => {},
  //   },
  // },
  data() {
    return {
      chart: null,
    };
  },
  // watch: {
  //   option: {
  //     handler(newValue, oldValue) {
  //       this.chart.setOption(newValue);
  //     },
  //     deep: true,
  //   },
  // },
  mounted() {
    this.chart = echarts.init(this.$refs.chartEl);
    // this.chart.setOption(this.option);

    // 添加窗口改变监听,增加节流，每隔200ms执行
    this.chart._resize = this.throttle(() => {
      this.chart.resize();
    }, 200);

    window.addEventListener("resize", this.chart._resize);
  },
  beforeDestroy() {
    // 移除窗口改变监听
    window.removeEventListener("resize", this.chart._resize);
  },
  methods: {
    // 节流函数,来自Lodash，这里可以自己写一个简单点的
    // 如果有多个地方用到，也可以使用引入的方式
    throttle(func, wait, options) {
      let time, context, args;
      let previous = 0;
      if (!options) options = {};

      const later = function () {
        previous = options.leading === false ? 0 : new Date().getTime();
        time = null;
        func.apply(context, args);
        if (!time) context = args = null;
      };

      const throttled = function () {
        const now = new Date().getTime();
        if (!previous && options.leading === false) previous = now;
        const remaining = wait - (now - previous);
        context = this;
        args = arguments;
        if (remaining <= 0 || remaining > wait) {
          if (time) {
            clearTimeout(time);
            time = null;
          }
          previous = now;
          func.apply(context, args);
          if (!time) context = args = null;
        } else if (!time && options.trailing !== false) {
          time = setTimeout(later, remaining);
        }
      };
      return throttled;
    },
    // 去除props,添加methods
    setOption(option) {
      console.log(12,option)
      this.chart && this.chart.setOption(option);
    },
  },
};
</script>
